import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/base/application.dart';
import 'package:panda/entity/my_exam_order_entity.dart';
import 'package:panda/event/UserInfoEvent.dart';
import 'package:panda/event/order_refresh.dart';
import 'package:panda/home/ChildListOrder.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/DateUtils.dart';
import 'package:panda/util/SignUtil.dart';

class MyShopCarPage extends StatefulWidget {
  var type;
  MyShopCarPage({Key key, @required this.type}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    return MyShopCarFragmentState();
  }
}

class MyShopCarFragmentState extends State<MyShopCarPage>
    with WidgetsBindingObserver, AutomaticKeepAliveClientMixin {
  final SlidableController slidableController = SlidableController();

  EasyRefreshController _controller = new EasyRefreshController();
  List<bool> bools = new List();
  int currentStatus = 0;
  bool isSelectAll = false;
  var time1 = "", time2 = "", time3 = "", time4 = "", current = "";
  String token = "";
  int page = 1;
  List<MyExamOrderDataData> dataList = new List();
  int allNum = 0;
  double allPrice = 0;
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      getString(TOKEN).then((value) {
        token = value;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    bools..add(false)..add(false)..add(false)..add(false)..add(false);
    var today = DateTime.now();
    var fiftyDaysFromNow = today.subtract(new Duration(days: 0));
    time1 = DateUtils.instance.getFormartData(
        timeSamp: fiftyDaysFromNow.millisecondsSinceEpoch,
        format: "yyyy-MM-dd");
    current = time1;
    fiftyDaysFromNow = today.subtract(new Duration(days: 1));
    time2 = DateUtils.instance.getFormartData(
        timeSamp: fiftyDaysFromNow.millisecondsSinceEpoch,
        format: "yyyy-MM-dd");
    fiftyDaysFromNow = today.subtract(new Duration(days: 2));
    time3 = DateUtils.instance.getFormartData(
        timeSamp: fiftyDaysFromNow.millisecondsSinceEpoch,
        format: "yyyy-MM-dd");
    setState(() {});
    getString(TOKEN).then((value) {
      token = value;
      loadList();
    });
    APPLIC.eventBus.on<OrderRefreshEvent>().listen((event) {
      if(event.index=="2"){
        getString(TOKEN).then((value) {
          token = value;
          page = 1;
          loadList();
        });
      }
    });
  }

  loadList() async {
    Map map = new Map();
    map['token'] = token;
    map['type'] = widget.type;
    map['p'] = page;
    map['per'] = 10;
    map['date'] = current;
    map['sign_type'] = SignType.GET_MY_EXAMINEORDERLIST;
    Response<String> response =
        await HttpUtil().post(Api.GET_MY_EXAMINEORDERLIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] != 1) {
      Fluttertoast.showToast(msg: userMap['msg']);
      return;
    }
    MyExamOrderEntity homeListEntity = new MyExamOrderEntity.fromJson(userMap);
    if (mounted)
      setState(() {
        if (page == 1) {
          dataList.clear();
          isSelectAll = false;
          allNum = 0;
          dataList.addAll(homeListEntity.data.datas);
        } else {
          dataList.addAll(homeListEntity.data.datas);
        }
        if (page == 1) {
          _controller.resetLoadState();
          _controller.finishRefresh();
        } else {
          _controller.finishLoad(noMore: homeListEntity.data.datas.length == 0);
          if (homeListEntity.data.datas.length == 0) {
            Fluttertoast.showToast(msg: "暂无更多数据");
          }
        }
      });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return AnnotatedRegion<SystemUiOverlayStyle>(
      child: Column(
        children: <Widget>[
          Offstage(
            offstage: widget.type == 1,
            child: Container(
              color: f0Color,
              padding: EdgeInsets.all(10),
              child: Row(
                children: <Widget>[
                  Expanded(
                    flex: 1,
                    child: GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        child: Container(
                          padding: EdgeInsets.all(
                              ScreenUtil.getInstance().setHeight(DP_10)),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: current == time1 ? Colors.red[100] : grey,
                              borderRadius: BorderRadius.circular(5)),
                          child: Text(time1,
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE),
                                  color: current == time1
                                      ? mainColor
                                      : Colors.black87)),
                        ),
                        onTap: () {
                          current = time1;
                          setState(() {});
                          page = 1;
                          loadList();
                        }),
                  ),
                  Container(
                    width: ScreenUtil.getInstance().setHeight(DP_10),
                  ),
                  Expanded(
                    flex: 1,
                    child: GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        child: Container(
                          padding: EdgeInsets.all(
                              ScreenUtil.getInstance().setHeight(DP_10)),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: current == time2 ? Colors.red[100] : grey,
                              borderRadius: BorderRadius.circular(5)),
                          child: Text(time2,
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE),
                                  color: current == time2
                                      ? mainColor
                                      : Colors.black87)),
                        ),
                        onTap: () {
                          current = time2;
                          setState(() {});
                          page = 1;
                          loadList();
                        }),
                  ),
                  Container(
                    width: ScreenUtil.getInstance().setHeight(DP_10),
                  ),
                  Expanded(
                    flex: 1,
                    child: GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        child: Container(
                          padding: EdgeInsets.all(
                              ScreenUtil.getInstance().setHeight(DP_10)),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: current == time3 ? Colors.red[100] : grey,
                              borderRadius: BorderRadius.circular(5)),
                          child: Text(time3,
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE),
                                  color: current == time3
                                      ? mainColor
                                      : Colors.black87)),
                        ),
                        onTap: () {
                          current = time3;
                          setState(() {});
                          page = 1;
                          loadList();
                        }),
                  ),
                  Container(
                    width: ScreenUtil.getInstance().setHeight(DP_10),
                  ),
                  GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      child: Row(
                        children: <Widget>[
                          Text("全部",
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE - 2),
                                  color: current == ""
                                      ? mainColor
                                      : Colors.black)),
                          Icon(Icons.arrow_drop_down,
                              color: current == "" ? mainColor : Colors.black),
                        ],
                      ),
                      onTap: () {
                        current = "";
                        setState(() {});
                        page = 1;
                        loadList();
                      })
                ],
              ),
            ),
          ),
          Expanded(
            child: new EasyRefresh(
              controller: _controller,
              header: MaterialHeader(),
              footer: MaterialFooter(),
              enableControlFinishRefresh: true,
              child: ListView.separated(
                itemCount: dataList.length,
                itemBuilder: (BuildContext context, int index) {
                  return renderView(context, index);
                },
                separatorBuilder: (BuildContext context, int index) {
                  return Container(height: 10);
                },
              ),
              onRefresh: () {
                page = 1;
                loadList();
              },
              onLoad: () {
                page++;
                loadList();
              },
            ),
          ),
          // Container(
          //   height: 0.5,
          //   color: f0Color,
          // ),
          // Offstage(
          //   offstage: widget.type != 1,
          //   child: Container(
          //     color: white,
          //     padding: EdgeInsets.fromLTRB(
          //         ScreenUtil.getInstance().setHeight(5),
          //         ScreenUtil.getInstance().setHeight(DP_10),
          //         ScreenUtil.getInstance().setHeight(DP_20),
          //         ScreenUtil.getInstance().setHeight(DP_10)),
          //     child: Row(
          //       children: <Widget>[
          //         CircularCheckBox(
          //             value: isSelectAll,
          //             activeColor: mainColor,
          //             inactiveColor: black_99,
          //             materialTapTargetSize: MaterialTapTargetSize.padded,
          //             onChanged: (bool x) {
          //               isSelectAll = !isSelectAll;
          //               checkAll();
          //               setState(() {});
          //             }),
          //         Text('全选',
          //             style: TextStyle(
          //                 fontSize:
          //                     ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
          //                 color: Colors.black87)),
          //         Container(
          //           width: 20,
          //         ),
          //         Text(currentStatus == 0 ? '合计：' : '',
          //             style: TextStyle(
          //                 fontSize: ScreenUtil.getInstance()
          //                     .setSp(NORMAL_FONT_SIZE),
          //                 color: Colors.black)),
          //         Text(currentStatus == 0 ? ('$allNum 单') : '',
          //             style: TextStyle(
          //                 fontSize: ScreenUtil.getInstance()
          //                     .setSp(NORMAL_FONT_SIZE),
          //                 color: mainColor)),
          //         Expanded(
          //           child: Text(''),
          //         ),
          //         new Container(
          //           height: ScreenUtil.getInstance().setHeight(DP_60),
          //           decoration: new BoxDecoration(
          //               color: mainColor,
          //               borderRadius: BorderRadius.circular(20.0)),
          //           padding: EdgeInsets.fromLTRB(5.0, 0.0, 5.0, 0.0),
          //           child: new FlatButton(
          //             child: new Padding(
          //               padding: EdgeInsets.all(0.0),
          //               child: new Text(
          //                 currentStatus == 0 ? "确认下单" : '删除',
          //                 style: new TextStyle(
          //                     color: Colors.white,
          //                     fontSize: ScreenUtil.getInstance()
          //                         .setSp(NORMAL_FONT_SIZE)),
          //               ),
          //             ),
          //             onPressed: () {
          //               if (allNum == 0) {
          //                 Fluttertoast.showToast(msg: "请选择订单后再确认提交");
          //                 return;
          //               }
          //               String order_id = "";
          //               for (int i = 0; i < dataList.length; i++) {
          //                 if (dataList[i].isSelect) {
          //                   order_id += dataList[i].order_id + ",";
          //                 }
          //               }
          //               Navigator.of(context).push<String>(
          //                   new MaterialPageRoute(builder: (context) {
          //                 return new ConfirmOrderPage(
          //                   allPrice: allPrice,
          //                   allNum: allNum,
          //                   order_id:
          //                       order_id.substring(0, order_id.length - 1),
          //                 );
          //               })).then((value) {
          //                 if (value != null) {
          //                   page = 1;
          //                   loadList();
          //                 }
          //               });
          //             },
          //           ),
          //         )
          //       ],
          //     ),
          //   ),
          // )
        ],
      ),
      value: SystemUiOverlayStyle.dark,
    );
  }

  Widget renderView(BuildContext context, int index) {
    return new GestureDetector(
      onTap: () {
        // Navigator.of(context).push(MaterialPageRoute(builder: (context) {
        //   return new OrderDetailPage(
        //     id: dataList[index].id,
        //   );
        // }));
      },
      child: new Container(
        decoration: BoxDecoration(
            color: Colors.white, borderRadius: BorderRadius.circular(0.0)),
        padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Row(
              children: <Widget>[
                ClipOval(
                  child: dataList[index].head_img == null
                      ? Image.asset("images/app_icon.png",
                          width: ScreenUtil.getInstance().setHeight(DP_60),
                          height: ScreenUtil.getInstance().setHeight(DP_60),
                          fit: BoxFit.cover)
                      : CachedNetworkImage(
                imageUrl:
                          dataList[index].head_img.contains("http")
                              ? dataList[index].head_img
                              : Api.ImgBaseUrl + dataList[index].head_img,
                          width: ScreenUtil.getInstance().setHeight(DP_60),
                          height: ScreenUtil.getInstance().setHeight(DP_60),
                          fit: BoxFit.cover),
                ),
                Container(width: 10),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        new Text(
                          dataList[index].name == null
                              ? ""
                              : dataList[index].name,
                          style: new TextStyle(
                              color: black,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE)),
                        ),
                        Container(width: 5),
                        Container(
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(2),
                              border: Border.all(color: mainColor, width: 1)),
                          padding: EdgeInsets.fromLTRB(
                              ScreenUtil.getInstance().setHeight(DP_8),
                              0,
                              ScreenUtil.getInstance().setHeight(DP_8),
                              0),
                          margin: EdgeInsets.fromLTRB(0, 0,
                              ScreenUtil.getInstance().setHeight(DP_10), 0),
                          child: Text(
                            dataList[index].group_name,
                            style: TextStyle(
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(MINI_FONT_SIZE),
                                color: mainColor),
                          ),
                        )
                      ],
                    ),
                    Container(height: 3),
                    new Text(
                      dataList[index].create_time,
                      style: new TextStyle(
                          color: Colors.black45,
                          fontSize:
                              ScreenUtil.getInstance().setSp(MINI_FONT_SIZE)),
                    ),
                  ],
                ),
                Expanded(
                  child: Center(),
                ),
                // Offstage(
                //   offstage: widget.type != 1,
                //   child: CircularCheckBox(
                //       value: dataList[index].isSelect,
                //       activeColor: mainColor,
                //       inactiveColor: black_99,
                //       materialTapTargetSize: MaterialTapTargetSize.padded,
                //       onChanged: (bool x) {
                //         dataList[index].isSelect = !dataList[index].isSelect;
                //         allNum = 0;
                //         allPrice = 0;
                //         for (int i = 0; i < dataList.length; i++) {
                //           if (dataList[index].isSelect)
                //             allNum += int.parse(dataList[i].num);
                //           allPrice += double.parse(dataList[i].allprice);
                //         }
                //         setState(() {});
                //       }),
                // )
              ],
            ),
            Container(height: 10),
            new GestureDetector(
              child: Container(
                padding: EdgeInsets.fromLTRB(30, 20, 30, 20),
                decoration: BoxDecoration(
                  color: f0Color,
                  borderRadius: BorderRadius.circular(5),
                ),
                child: Row(
                  children: <Widget>[
                    new Text(
                      "总额:   ",
                      style: new TextStyle(
                          color: Colors.black54,
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                    ),
                    new Text(
                      MONEY + dataList[index].allprice,
                      style: new TextStyle(
                          color: mainColor,
                          fontSize:
                              ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
                    ),
                    Container(width: 30),
                    new Text(
                      "单数:   ",
                      style: new TextStyle(
                          color: Colors.black54,
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                    ),
                    new Text(
                      dataList[index].num,
                      style: new TextStyle(
                          color: mainColor,
                          fontSize:
                              ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
                    ),
                    new Text(
                      "个",
                      style: new TextStyle(
                          color: Colors.black54,
                          fontSize:
                              ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
                    ),
                  ],
                ),
              ),
              onTap: () {
                Navigator.of(context)
                    .push(new MaterialPageRoute(builder: (context) {
                  return new ChildOrderListPage(
                      id: dataList[index].parameter, type: "3");
                }));
              },
              behavior: HitTestBehavior.opaque,
            ),
            Container(
              height: 10,
            ),
            Row(
              children: <Widget>[
                Expanded(
                    //   child: Offstage(
                    // offstage: widget.type != 3,
                    child: new Text(
                  "积分兑换: " +
                      (dataList[index].point == "null"
                          ? "0"
                          : dataList[index].point),
                  style: new TextStyle(
                      color: Colors.black87,
                      fontSize:
                          ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE + 2)),
                  // ),
                )),
                new Text(
                  (widget.type == 1 ? '应交金额: ' : "已交金额: ") +
                      formatNum((double.parse(dataList[index].allprice) -
                              double.parse(dataList[index].point == "null"
                                  ? "0"
                                  : dataList[index].point)), 2)
                         ,
                  style: new TextStyle(
                      color: Colors.black87,
                      fontSize:
                          ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE + 2)),
                ),
              ],
            ),
            Container(
              height: 10,
            ),
            Offstage(
                offstage: widget.type != 3,
                child: new Text(
                  "备注:",
                  style: new TextStyle(
                      color: Colors.black87,
                      fontSize:
                          ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE + 2)),
                ))
          ],
        ),
      ),
    );
  }
String formatNum(double num, int postion) {
    if ((num.toString().length - num.toString().lastIndexOf(".") - 1) <
        postion) {
      return num.toStringAsFixed(postion)
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    } else {
      return num.toString()
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    }
  }
  checkAll() {
    allNum = 0;
    allPrice = 0;
    for (int i = 0; i < dataList.length; i++) {
      dataList[i].isSelect = isSelectAll;
      if (isSelectAll) {
        allNum += int.parse(dataList[i].num);
        allPrice += double.parse(dataList[i].allprice);
      }
    }
    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this); //销毁观���者
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    return false;
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
